<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <title>HTML5的本地存储之localstorage | 默默地向前端靠拢</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="开门见山，今天来讲一讲HTML5中的存储方式。前端开发者应该都知道，对于html的本地存储是HTML5中出现的新特性，并不是所有浏览器都支持，在开始写本地存储的时候，必须得检测一下浏览器对本地存储特性的支持性是否良好，根据支持情况选择不同的方案，以免造成不必要的麻烦。">
<meta name="keywords" content="HTML5">
<meta property="og:type" content="article">
<meta property="og:title" content="HTML5的本地存储之localstorage">
<meta property="og:url" content="http://yoursite.com/2016/04/22/HTML5的本地存储之localstorage/index.html">
<meta property="og:site_name" content="默默地向前端靠拢">
<meta property="og:description" content="开门见山，今天来讲一讲HTML5中的存储方式。前端开发者应该都知道，对于html的本地存储是HTML5中出现的新特性，并不是所有浏览器都支持，在开始写本地存储的时候，必须得检测一下浏览器对本地存储特性的支持性是否良好，根据支持情况选择不同的方案，以免造成不必要的麻烦。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-02-13T08:52:43.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="HTML5的本地存储之localstorage">
<meta name="twitter:description" content="开门见山，今天来讲一讲HTML5中的存储方式。前端开发者应该都知道，对于html的本地存储是HTML5中出现的新特性，并不是所有浏览器都支持，在开始写本地存储的时候，必须得检测一下浏览器对本地存储特性的支持性是否良好，根据支持情况选择不同的方案，以免造成不必要的麻烦。">
  
    <link rel="alternative" href="/atom.xml" title="默默地向前端靠拢" type="application/atom+xml">
  
  
    <link rel="icon" href="/img/head.jpg">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/img/head.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">心情</a></h1>
		</hgroup>

		
		<p class="header-subtitle">你所浪费的今天，是昨天死去的人奢望的明天；你所厌恶的现在，是未来的你回不去的曾经。</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
						<div class="icon-wrap icon-me hide" data-idx="3">
							<div class="user"></div>
							<div class="shoulder"></div>
						</div>
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
						<li>关于我</li>
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/">主页</a></li>
				        
							<li><a href="/archives">所有文章</a></li>
				        
							<li><a href="/categories/随笔">随笔总结</a></li>
				        
							<li><a href="/categories/笔记">学习笔记</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
								<a class="github" target="_blank" href="http://springxiege.gitbub.io" title="github">github</a>
					        
								<a class="weibo" target="_blank" href="http://weibo.com/springxiegel" title="weibo">weibo</a>
					        
								<a class="mail" target="_blank" href="mailto://springxiege@sina.cn" title="mail">mail</a>
					        
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						<a href="/tags/Git/" style="font-size: 10px;">Git</a> <a href="/tags/HTML5/" style="font-size: 10px;">HTML5</a> <a href="/tags/JS/" style="font-size: 20px;">JS</a> <a href="/tags/JavaScript/" style="font-size: 13.33px;">JavaScript</a> <a href="/tags/Node/" style="font-size: 10px;">Node</a> <a href="/tags/NodeJS/" style="font-size: 16.67px;">NodeJS</a> <a href="/tags/NodeJs/" style="font-size: 10px;">NodeJs</a> <a href="/tags/React-js/" style="font-size: 13.33px;">React.js</a> <a href="/tags/hexo/" style="font-size: 10px;">hexo</a>
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://www.52cik.com/">乱码大大的博客</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://webcaiqingchong.github.io/">菜青虫的博客</a>
			        
			        </div>
				</section>
				

				
				
				<section class="switch-part switch-part4">
				
					<div id="js-aboutme">我是心情，我是一名前端工作者，目前靠Coding讨生活！平时喜欢玩三国杀，听音乐，运动也喜欢，只是现在运动项目做得少了。</div>
				</section>
				
			</div>
		</div>
	</header>				
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">心情</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
			
				<img lazy-src="/img/head.jpg" class="js-avatar">
			
			</div>
			<hgroup>
			  <h1 class="header-author">心情</h1>
			</hgroup>
			
			<p class="header-subtitle">你所浪费的今天，是昨天死去的人奢望的明天；你所厌恶的现在，是未来的你回不去的曾经。</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/">主页</a></li>
		        
					<li><a href="/archives">所有文章</a></li>
		        
					<li><a href="/categories/随笔">随笔总结</a></li>
		        
					<li><a href="/categories/笔记">学习笔记</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
						<a class="github" target="_blank" href="http://springxiege.gitbub.io" title="github">github</a>
			        
						<a class="weibo" target="_blank" href="http://weibo.com/springxiegel" title="weibo">weibo</a>
			        
						<a class="mail" target="_blank" href="mailto://springxiege@sina.cn" title="mail">mail</a>
			        
				</div>
			</nav>
		</header>				
	</div>
</nav>

      <div class="body-wrap"><article id="post-HTML5的本地存储之localstorage" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/2016/04/22/HTML5的本地存储之localstorage/" class="article-date">
  	<time datetime="2016-04-22T12:47:45.000Z" itemprop="datePublished">2016-04-22</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      HTML5的本地存储之localstorage
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
	<div class="article-tag tagcloud">
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/HTML5/">HTML5</a></li></ul>
	</div>

        
	<div class="article-category tagcloud">
	<a class="article-category-link" href="/categories/随笔/">随笔</a>
	</div>


        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>开门见山，今天来讲一讲HTML5中的存储方式。前端开发者应该都知道，对于html的本地存储是HTML5中出现的新特性，并不是所有浏览器都支持，在开始写本地存储的时候，必须得检测一下浏览器对本地存储特性的支持性是否良好，根据支持情况选择不同的方案，以免造成不必要的麻烦。<a id="more"></a><br>在Web Storage API中，特定域名下的Storage数据库可以直接通过window对象访问。因此首先确定用户的浏览器是不支持Web Storage非常重要。代码示例如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">checkStorageSupport</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">if</span>(<span class="built_in">window</span>.localStorage)&#123;</div><div class="line">        alert(<span class="string">'This browser supports localStorage'</span>);</div><div class="line">    &#125;<span class="keyword">else</span>&#123;</div><div class="line">        alert(<span class="string">'This browser does not supports localStorage'</span>);</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>上面只是说明了检测浏览是否支持localStorage，接下来，再详细扒一扒本地存储的API方法:<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">setItem(key,val);</div><div class="line">removeItem(key);</div><div class="line">getItem(key);</div><div class="line">clear();</div><div class="line">key(index);</div></pre></td></tr></table></figure></p>
<p>上面的代码是通过setItem方法设置数据的，key为关键字类似字段名形式，val则表示相对应的值，不过在这里要提一下的是，这种方法设置的的数据都是以字符串的形式存储的。以上原生方法就介绍到这里。<br>下面我再说说一个非常实用的开源项目store.js，这个开源小库非常实用，那么我们开始吧</p>
<p>首先，先介绍一下关于store.js的简单API：（store.js exposes a simple API for cross browser local storage）<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div></pre></td><td class="code"><pre><div class="line"></div><div class="line"><span class="comment">// Store 'marcus' at 'username'</span></div><div class="line">store.set(<span class="string">'username'</span>, <span class="string">'marcus'</span>)</div><div class="line"></div><div class="line"><span class="comment">// Get 'username'</span></div><div class="line">store.get(<span class="string">'username'</span>)</div><div class="line"></div><div class="line"><span class="comment">// Remove 'username'</span></div><div class="line">store.remove(<span class="string">'username'</span>)</div><div class="line"></div><div class="line"><span class="comment">// Clear all keys</span></div><div class="line">store.clear()</div><div class="line"></div><div class="line"><span class="comment">// Store an object literal - store.js uses JSON.stringify under the hood</span></div><div class="line">store.set(<span class="string">'user'</span>, &#123; <span class="attr">name</span>: <span class="string">'marcus'</span>, <span class="attr">likes</span>: <span class="string">'javascript'</span> &#125;)</div><div class="line"></div><div class="line"><span class="comment">// Get the stored object - store.js uses JSON.parse under the hood</span></div><div class="line"><span class="keyword">var</span> user = store.get(<span class="string">'user'</span>)</div><div class="line">alert(user.name + <span class="string">' likes '</span> + user.likes)</div><div class="line"></div><div class="line"><span class="comment">// Get all stored values</span></div><div class="line">store.getAll().user.name == <span class="string">'marcus'</span></div><div class="line"></div><div class="line"><span class="comment">// Loop over all stored values</span></div><div class="line">store.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">key, val</span>) </span>&#123;</div><div class="line">    <span class="built_in">console</span>.log(key, <span class="string">'=='</span>, val)</div><div class="line">&#125;)</div></pre></td></tr></table></figure></p>
<p>基于这个开源库，我们检测浏览器是否支持本地存储的代码则更为简单了：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// store.enabled 返回一个布尔值，如果浏览器支持本地存储则返回true,否则返回false</span></div><div class="line"><span class="keyword">if</span> (!store.enabled) &#123;</div><div class="line">    alert(<span class="string">'Local storage is not supported by your browser. Please disable "Private Mode", or upgrade to a modern browser.'</span>);</div><div class="line">    <span class="keyword">return</span> ;</div><div class="line">&#125;</div></pre></td></tr></table></figure></p>
<p>以上是store.js的主要API，这些都不是重点，重点是我要基于这个开源小库封装一下自己的一个小方法，对于大部分人来说，或许这步是多余的，如有多余，请勿喷。。。。</p>
<p>由于通过store.js保存的数据是字符串形式的，所以我存储数据时做了如下处理：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/**</span></div><div class="line"><span class="comment"> * [setStorage 利用store.js改进存储方法，用来存储json对象字符串]</span></div><div class="line"><span class="comment"> * @param &#123;[type]&#125; objName [存储的key值名字]</span></div><div class="line"><span class="comment"> * @param &#123;[type]&#125; key     [存储json对象的key值]</span></div><div class="line"><span class="comment"> * @param &#123;[type]&#125; val     [存储json对象的对应value值]</span></div><div class="line"><span class="comment"> */</span></div><div class="line"><span class="keyword">var</span> setStorage = <span class="function"><span class="keyword">function</span>(<span class="params">objName,key,val</span>)</span>&#123;</div><div class="line">    <span class="keyword">var</span> _data = &#123;&#125;;</div><div class="line">    _data[objName] = &#123;&#125;;</div><div class="line">    _data[objName].data = store.get(objName)||&#123;&#125;;</div><div class="line">    _data[objName].data[key] = val;</div><div class="line">    store.set(objName,_data[objName].data);</div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>估计有人看到上面的代码会有疑问，那就是store.js明明有自己的一套获取数据的方法，为什么还要重新写一个呢？<br>对于这个疑问，就让大家自己先思考一下吧，上面重新写的获取方法或许会对你有帮助哟！</p>
<p>总结：在我被要求优化一个组件的时候，里面有就一条，将数据存储到本地，我就用了store.js这个开源，挺方便的，不过随之在用的过程中遇到了不小的坑，可能是刚开始接触的时候对它的本质不太了解，所以才会掉进坑里去，上面自定义的存储数据方法是我解决坑的方案，用这个方法着实给我减轻了不小的负担。另外，希望这篇文章对前端的你有帮助！</p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2016/04/22/JS实现倒计时/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption"><</strong>
      <div class="article-nav-title">
        
          JS实现倒计时
        
      </div>
    </a>
  
  
</nav>

  
</article>


<div class="share share_jia">
	<!-- JiaThis Button BEGIN -->
	<div class="jiathis_style">
		<span class="jiathis_txt">分享到: &nbsp; </span>
		<a class="jiathis_button_facebook"></a> 
    <a class="jiathis_button_twitter"></a>
    <a class="jiathis_button_plus"></a> 
    <a class="jiathis_button_tsina"></a>
		<a class="jiathis_button_cqq"></a>
		<a class="jiathis_button_douban"></a>
		<a class="jiathis_button_weixin"></a>
		<a class="jiathis_button_tumblr"></a>
    <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
	</div>
	<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=1405949716054953" charset="utf-8"></script>
	<!-- JiaThis Button END -->
</div>






<div class="duoshuo">
	<!-- 多说评论框 start -->
	<div class="ds-thread" data-thread-key="HTML5的本地存储之localstorage" data-title="HTML5的本地存储之localstorage" data-url="http://yoursite.com/2016/04/22/HTML5的本地存储之localstorage/"></div>
	<!-- 多说评论框 end -->
	<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"true"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] 
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
	</script>
	<!-- 多说公共JS代码 end -->
</div>




</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2017 心情
    	</div>
      	<div class="footer-right">
      		<a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
      	</div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="http://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
<script src="/js/main.js"></script>






<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  </div>
</body>
</html>